<template>
  <el-upload
    ref="upload"
    class="avatar-uploader"
    action="#"
    list-type="picture-card"
    :auto-upload="true"
    :on-exceed="doExceed"
    :http-request="doFileUpload"
    :show-file-list="false"
    :before-upload="doBeforeUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else ><Plus /></el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, genFileId, type UploadFile, type UploadInstance, type UploadProps, type UploadRawFile, type UploadRequestOptions } from 'element-plus';
import { uploadFileUsingPost } from '@/api/fileController';
import { ResponseCodeEnum } from '@/enums';

// 从父组件接收文件上传类型, 文件路径暴露出去
const { fileUploadType, imageUrl } = defineProps(["fileUploadType", "imageUrl"])
const emit = defineEmits(["update:imageUrl"])

/**
 * 自定义上传文件方法
 */
const doFileUpload = async (option: UploadRequestOptions) => {
  const result: any = await uploadFileUsingPost(
    { fileUploadType },
    {},
    option.file
  );

  if (result.data.code == ResponseCodeEnum.SUCCESS && result.data.data) {
    ElMessage.success("上传成功 (但需要提交才能保存)")
    
    // 更新 imageUrl 的值
    emit('update:imageUrl', result.data.data)
  } else {
    ElMessage.error("上传失败: " + result.data.message)
  }
}

const doBeforeUpload = (file: UploadFile) => {
  // 这里可以添加文件校验
}

const upload = ref<UploadInstance>()

/**
 * 替换已提交图片
 * @param files 
 */
const doExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

</script>

<style scoped lang="less">
.avatar-uploader {
  // box-shadow: 0 0 0 1px rgb(220, 223, 230);
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  // box-shadow: 0 0 0 1px #c0c4cc;
}

.avatar-uploader .el-upload--picture-card {
  border: 0;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 95%;
  height: 95%;
  object-fit: cover;
  border-radius: 4px;
}
</style>